import {ConfigStore} from '../storage/configStore';
import {InterceptorConfig, RequestInterceptor} from './base';
import {XHRInterceptor} from './xhr';
import {FetchInterceptor} from './fetch';


export class InterceptorManager {
    private interceptors: RequestInterceptor[] = [];
    private config: InterceptorConfig = {
        apiConfig: [],
        globalHeaders: {},
        proxyConfigs: []
    };

    constructor() {
        this.updateConfig();
    }

    private updateConfig() {
        const config = ConfigStore.getConfig();
        this.config = {
            apiConfig: config.apiConfig || [],
            globalHeaders: config.globalHeaders || {},
            proxyConfigs: config.proxyConfigs || []
        };
        console.log('📝 当前配置:', this.config);
    }

    init() {
        // 更新最新配置
        this.updateConfig();

        // 初始化所有拦截器
        this.interceptors = [
            new XHRInterceptor(this.config),
            new FetchInterceptor(this.config)
        ];

        // 启动所有拦截器
        this.interceptors.forEach(interceptor => {
            try {
                interceptor.init();
            } catch (error) {
                console.error('拦截器初始化失败:', error);
            }
        });

        // 监听配置变化
        ConfigStore.addChangeListener(this.handleConfigChange);
        console.log('🎉 拦截器管理器初始化完成');
    }

    destroy() {
        // 销毁所有拦截器
        this.interceptors.forEach(interceptor => {
            try {
                interceptor.destroy();
            } catch (error) {
                console.error('拦截器销毁失败:', error);
            }
        });

        // 移除配置变化监听
        ConfigStore.removeChangeListener(this.handleConfigChange);
        console.log('🛑 拦截器管理器已销毁');
    }

    private handleConfigChange = () => {
        console.log("🔄 配置发生变化，重新初始化拦截器");
        // 配置发生变化，重新初始化拦截器
        this.destroy();
        this.updateConfig();
        this.init();
    };
} 